﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Net;
using System.Web;
using System.Web.Routing;

namespace yq.ControllerBase
{
    public class ErrorFilterAttribute : ActionFilterAttribute
    {
        public string ErrorText { get; set; }
        public ErrorFilterType ErrorType { get; set; }
        public string Title { get; set; }

        public ErrorFilterAttribute(string _ErrorText = "未定义错误原因", ErrorFilterType _ErrorType = ErrorFilterType.Default)
        {
            ErrorText = _ErrorText;
            ErrorType = _ErrorType;
        }

      
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            OnAction(filterContext);
        }
        
        /// <summary>
        /// 处理异常
        /// </summary>
        /// <param name="filterContext"></param>
        public  void OnAction(ActionExecutedContext filterContext)
        {
            var Request = filterContext.HttpContext.Request;
            var Response = filterContext.HttpContext.Response;

            //是否发生了错误
            if (filterContext.Exception == null || filterContext.ExceptionHandled)
            {
                return;
            }

            //写入异常
            yq.Log.Record.WriteAsyn(ErrorText, filterContext.Exception.ToString(), Log.LogLevel.Default);

            //如果是开发模式写入异常消息
            if (yq.ControllerBase.WebConfig.IsDevelop && ErrorType != ErrorFilterType.AlertGoBack)
            {
                ErrorText = "<H2>" + ErrorText + "</H2><BR/>在开发模式错误提示：" + filterContext.Exception.ToString();
            }

            //将异常修改为207
            Response.StatusCode = 207;
            //设置异常已捕获
            filterContext.ExceptionHandled = true;
            //设置不跳到500页面
            filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
            

            filterContext.Result = GetError(ErrorType, ErrorText, filterContext.Controller);
            
        }
        
        
        /// <summary>
        /// 根据错误配置设置错误处理方式
        /// </summary>
        /// <param name="type"></param>
        /// <param name="errorText"></param>
        /// <param name="httpContext"></param>
        /// <returns></returns>
        public static ActionResult GetError(ErrorFilterType type, string errorText, System.Web.Mvc.ControllerBase controller)
        {
           
            if (type == ErrorFilterType.Default && controller.ControllerContext.HttpContext.Request.IsAjaxRequest())
            {
                type = ErrorFilterType.ReturnValue;
            }
            else if (type == ErrorFilterType.Default)
            {
                type = ErrorFilterType.ErrorPage;
            }

            if (type == ErrorFilterType.ReturnValue)
            {
                return new JsonResult
               {
                   Data = new yq.Dictionary.ReturnValue<string>() { Status = yq.Dictionary.ReturnEnum.No, ErrorText = errorText },
                   ContentEncoding = System.Text.Encoding.UTF8,
                   JsonRequestBehavior = JsonRequestBehavior.AllowGet
               };
            }
            else if (type == ErrorFilterType.AlertGoBack)
            {
                return new ContentResult()
                {
                    Content = "<script >alert('" + errorText + "');history.back();</script>",
                    ContentEncoding = System.Text.Encoding.UTF8
                };
            }
            else if (type == ErrorFilterType.Text)
            {
                return new ContentResult()
                {
                    Content = errorText,
                    ContentEncoding = System.Text.Encoding.UTF8
                };
            }
            else 
            {
                string guid = "Guid".ExtNewGuid();
                controller.TempData[guid] = errorText;
                
                return new RedirectResult(yq.ControllerBase.WebConfig.Error500 + "?errorGuid=" + guid);
            }
        }


    }


    /// <summary>
    /// 方法返回值类型
    /// </summary>
    public enum ErrorFilterType
    {
        /// <summary>
        /// 表示将返回yd.Util.ReturnValues（Ajax）类型的对象
        /// </summary>
        ReturnValue = 1,
        /// <summary>
        /// 去错误页面
        /// </summary>
        ErrorPage = 2,
        /// <summary>
        /// 返回并且弹出提示
        /// </summary>
        AlertGoBack = 3,

        /// <summary>
        /// 文本提示
        /// </summary>
        Text = 4,

        /// <summary>
        /// 默认处理
        /// </summary>
        Default = 0
    }


}
